package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    /**
     * 新增菜品和对应口味
     * @param dishDTO
     */
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //向菜品表加一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        //向口味表加n条数据
        if(flavors != null && flavors.size() >0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Transactional
    public void deleteByIds(List<Long> ids) {
        //判断是否有起售菜品
        //TODO 逻辑还没理清楚
        for(Long id :ids){
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断是否有关联菜品
        List<Long> setmealIdsByDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIdsByDishIds != null && setmealIdsByDishIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        }
        //删除菜品表中的菜品数量(可优化)
//        for(Long id :ids) {
//            dishMapper.deleteById(id);
//            //删除菜品关联的口味数据
//            dishFlavorMapper.deleteById(id);
//        }

        //根据集合批量删除而不使用循环
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByIds(ids);




    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    public DishVO findById(Long id) {
        //查询菜品
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        //查询菜品口味
        List<DishFlavor> flavors = dishFlavorMapper.findById(id);
        dishVO.setFlavors(flavors);
        return dishVO;

    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Transactional
    public void update(DishDTO dishDTO) {
        //修改菜品(这里使用Dish更好)
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //修改菜品口味(先删除后添加)
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //先删除原有口味
        dishFlavorMapper.deleteById(dishDTO.getId());
        //添加原有口味，注意没有口味的情况逻辑和插入相同
        if(flavors != null && flavors.size() >0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 根据种类查询菜名集合
     * @param categoryId
     * @return
     */
    public List<Dish> findByCategoryId(Long categoryId) {
        List<Dish> dishs = dishMapper.getByCategoryId(categoryId);
        return dishs;
    }

    /**
     * 根据种类id查询菜名和口味集合
     * @param categoryId
     * @return
     */
    public List<DishVO> findWithFlavorsByCategoryId(Long categoryId) {
        //查询菜品
        List<Dish> dishs = dishMapper.getByCategoryId(categoryId);
        List<DishVO> dishVOS = new ArrayList<>();
        for(int i = 0; i < dishs.size();i++){
            dishVOS.add(new DishVO());
            BeanUtils.copyProperties(dishs.get(i),dishVOS.get(i));
        }

        //查询每个菜品的口味
        for(DishVO dishvo : dishVOS){
            List<DishFlavor> dishFlavors = dishFlavorMapper.findById(dishvo.getId());
            dishvo.setFlavors(dishFlavors);
        }
        return dishVOS;
    }


    /**
     * 修改起售停售状态
     * @param status
     * @param id
     */
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
    }
}
